
using System;
using System.ComponentModel;
using System.Xml.Linq;
using WpfPropertyEditorExtension;

namespace WpfXamlPropertyGridVSIX
{
    internal class XElementPropertyDescriptor : PropertyDescriptor
    {
        private readonly XElement _element;
        private readonly XAttribute _attribute;
        private readonly XamlEditorService _svc;

        public XElementPropertyDescriptor(XElement element, XAttribute attribute, XamlEditorService svc)
            : base(attribute.Name.ToString(), null)
        {
            _element = element;
            _attribute = attribute;
            _svc = svc;
        }

        public override bool CanResetValue(object component) => true;
        public override Type ComponentType => typeof(XElementWrapper);
        public override object GetValue(object component) => _attribute.Value;
        public override bool IsReadOnly => false;
        public override Type PropertyType => typeof(string);
        public override void ResetValue(object component) => _attribute.Value = string.Empty;
        public override bool ShouldSerializeValue(object component) => true;

        public override void SetValue(object component, object value)
        {
            _attribute.Value = value?.ToString() ?? "";
            _svc.UpdateStartTagOrContent(_element, updateContent:false);
        }
    }
}
